<?php
namespace classlib;
use \classlib\cache;
class mailer {
	/**
	 * 实现Email注册之后的自动跳转
	 * @param string $email
	 */
	public static function jump($email) {
		list(, $ltd) = explode('@', $email);
		$ckey = 'mail@'.$ltd;
		$url  = cache::inst()->get($ckey);
		if (!$url) {
			$url  = 'http://mail.'.$ltd;
			if (!self::status_code($url)) {
				$url  = 'http://'.$ltd;
				if (!self::status_code($url)) {
					$url  = '/';
				}
			}
			cache::inst()->set($ckey, $url);
		}
		return $url;
	}
	
	/**
	 * 获取请求的状态码资料信息
	 * @param string $url
	 * @param number $timesec
	 * @return bool
	 */
	public static function status_code($url, $timesec = 3) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timesec);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
		$info  = curl_exec($ch);
		if (!curl_errno($ch)) {
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($code == 200 || $code == 301 || $code == 302) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 发送邮件通知
	 * @param unknown $address
	 * @param unknown $title
	 * @param unknown $msg
	 * @param unknown $smtp
	 * @return boolean
	 */
	public static function send($address, $title, $msg, &$smtp) {
		static $mailer = FALSE;
		if (!$mailer) {
			require COREDIR.'/classlib/plugins/_phpmailer/class.phpmailer.php';
			$mailer = TRUE;
		}
		$mail 		= new PHPMailer();
		$mail->IsSMTP();
        $mail->SMTPDebug= false;
		$mail->CharSet	= 'UTF-8';
		$mail->Host 	= $smtp['stmp'];
		$mail->Port		= $smtp['port'];		
		$mail->SMTPAuth = $smtp['isauth'];
		$mail->Username = $smtp['user']; 
		$mail->Password = $smtp['loginpw']; 
		$mail->From 	= $smtp['from'];
		$mail->FromName = $smtp['fromname'];
		$mail->AddAddress($address);
		$mail->IsHTML(true); 
		$mail->Subject  = $title;
		$mail->Body     = $msg;
		if(!$mail->Send()) {
			return false;
		}
		return true;
	}
	
	/**
	 * 获取一台服务器的唯一标志码
	 * @return number
	 */
	public static function sysid() {
		$hash = cache::inst()->get('os@sysid');
		if (!is_numeric($hash)) {
			$str  = sprintf('%s%d', uniqid(), time());
			$hash = input::strhash($str);
			cache::inst()->set('os@sysid', $hash);
		}
		return $hash;
	}
	
	/**
	 * 开始执行一个发送脚本任务
	 */
	public static function start() {
		$script = '/src/bin/mail/script.php';
		$config = \classlib\core\config::load('config', false);
		if (isset($config['php']) && file_exists($config['php'])) {
			$queue = self::sysid();
			$locker= sem_get($queue);
			if (sem_acquire($locker, true)) {
				system($config['php']. ' '.COREDIR.$script.' > /dev/null 2>&1 &');
				sem_release($locker);
			}
			sem_remove($locker);
		}
	}
}